package com.sls.mall.ware.service.impl;

import com.sls.mall.common.utils.R;
import com.sls.mall.ware.feign.ProductFeignService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sls.mall.common.utils.PageUtils;
import com.sls.mall.common.utils.Query;

import com.sls.mall.ware.dao.WareSkuDao;
import com.sls.mall.ware.entity.WareSkuEntity;
import com.sls.mall.ware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {

    @Autowired
    WareSkuDao wareSkuDao;

    @Autowired
    ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuId))
        {
            queryWrapper.eq("sku_id",skuId);
        }

        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId))
        {
            queryWrapper.eq("ware_Id",wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {

        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<WareSkuEntity>().eq("sku_id",skuId).eq("ware_id",wareId);

        List<WareSkuEntity> wareSkuEntities = wareSkuDao.selectList(queryWrapper);

        if (wareSkuEntities == null || wareSkuEntities.size() == 0)
        {
            WareSkuEntity skuEntity = new WareSkuEntity();
            skuEntity.setId(skuId);
            skuEntity.setStock(skuNum);
            skuEntity.setWareId(wareId);
            skuEntity.setStockLocked(0);

            //远程查询sku 的名字，如果失败，整个事务无需回滚
            try
            {
                R info = productFeignService.info(skuId);
                if (info.getCode() == 0)
                {
                    Map<String,Object> map = (Map<String, Object>) info.get("skuInfo");
                    skuEntity.setSkuName((String) map.get("skuName"));
                }
            }catch (Exception e)
            {

            }

            wareSkuDao.insert(skuEntity);
        }else
        {
            wareSkuDao.addStock(skuId,wareId,skuNum);

        }


    }

}